//
//  DetailViewController.m
//  Expressions
//
//  Created by admin on 3/10/13.
//  Copyright (c) 2013 admin. All rights reserved.
//

#import "DetailViewController.h"
#import "ExpressionUtils.h"


@interface DetailViewController ()

@end

@implementation DetailViewController
@synthesize subjectDetailImages,subjectName, subjectNumber ,bannerIsVisible2, d, cellHeight;
@synthesize banerView = _banerView;

@synthesize customScrollView = _customScrollView;
@synthesize imageView = _imageView;
@synthesize arrayImage = _arrayImage;
@synthesize userManager = _userManager;
-(void)dealloc
{
    [_userManager release];
    [_arrayImage release];
    [_imageView release];
    [subjectDetailImages release];
    [subjectName release];
    [_customScrollView release];
    [super dealloc];
}
#pragma mark -
#pragma mark Mail/Print Method
-(void)print
{
    if (_arrayImage && _arrayImage.count >= 1) {
        NSString *strName = [_arrayImage objectAtIndex:0];
        UIImage *image = [UIImage imageNamed:strName];
        NSData *myData  = UIImageJPEGRepresentation(image, 1.0);
        [self print:myData filename:strName];
    }

}
-(void)print:(NSData *)data filename:(NSString *)filename
{
    Class printInteractionController = NSClassFromString(@"UIPrintInteractionController");
    UIPrintInteractionController *printInteraction;
	if ((printInteractionController != nil) && [printInteractionController isPrintingAvailable])
	{
		printInteraction = [printInteractionController sharedPrintController];
		if ([printInteractionController canPrintData:data] == YES) // Check first
		{
			UIPrintInfo *printInfo = [NSClassFromString(@"UIPrintInfo") printInfo];
            
			printInfo.duplex = UIPrintInfoDuplexLongEdge;
			printInfo.outputType = UIPrintInfoOutputGeneral;
			printInfo.jobName = filename;
            
			printInteraction.printInfo = printInfo;
			printInteraction.printingItem = data;
			printInteraction.showsPageRange = YES;
            
			if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
			{
				[printInteraction presentFromRect:self.view.frame inView:self.view animated:YES completionHandler:
                 ^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
                 {
                     if ((completed == NO) && (error != nil)){
                        NSLog(@"%s %@", __FUNCTION__, error);  
                     }
                 }
                 ];
			}
			else // Presume UIUserInterfaceIdiomPhone
			{
				[printInteraction presentAnimated:YES completionHandler:
                 ^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
                 {
                     if ((completed == NO) && (error != nil))
                     {
                         NSLog(@"%s %@", __FUNCTION__, error);
                     }
                     if (error == nil) {
                         [_arrayImage removeObjectAtIndex:0];
                         [self print];
                     }
                     
                 }];
			}
		}
	}

}
-(void)showMailPicker:(id)sender {
	Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
	if (mailClass != nil) {
		if ([mailClass canSendMail]) {
			[self displayMailComposerSheet];
		}
		else {
			// handle error
		}
	}
	else{
        // handle error
	}
}
-(void)displayMailComposerSheet
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	[picker setSubject:@""];
	// Set up recipients
	NSArray *toRecipients = [NSArray arrayWithObject:@"kachiusa236@gmail.com"];
	NSArray *ccRecipients = [NSArray arrayWithObjects:@"", nil];
	NSArray *bccRecipients = [NSArray arrayWithObjects:@"",nil];
	
	[picker setToRecipients:toRecipients];
	[picker setCcRecipients:ccRecipients];
	[picker setBccRecipients:bccRecipients];
	
	// Attach an image to the email
    for (NSString *strName in _arrayImage) {
        UIImage *image = [UIImage imageNamed:strName];
        NSData *myData  = UIImageJPEGRepresentation(image, 1.0);
        [picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:strName];
    }
	
	
	// Fill out the email body text
	NSString *emailBody = @"";
	[picker setMessageBody:emailBody isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	
	NSString *feedbackMsg;
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			feedbackMsg = @"Result: Mail sending canceled";
			break;
		case MFMailComposeResultSaved:
			feedbackMsg = @"Result: Mail saved";
			break;
		case MFMailComposeResultSent:
			feedbackMsg = @"Result: Mail sent";
			break;
		case MFMailComposeResultFailed:
			feedbackMsg = @"Result: Mail sending failed";
			break;
		default:
			feedbackMsg = @"Result: Mail not sent";
			break;
	}
    [self showAlert:feedbackMsg];
	[self dismissModalViewControllerAnimated:YES];
}


// Dismisses the message composition interface when users tap Cancel or Send. Proceeds to update the
// feedback message field with the result of the operation.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result {
	NSString *feedbackMsg;
	switch (result)
	{
		case MessageComposeResultCancelled:
			feedbackMsg = @"Result: SMS sending canceled";
			break;
		case MessageComposeResultSent:
			feedbackMsg = @"Result: SMS sent";
			break;
		case MessageComposeResultFailed:
			feedbackMsg = @"Result: SMS sending failed";
			break;
		default:
			feedbackMsg = @"Result: SMS not sent";
			break;
	}
    [self showAlert:feedbackMsg];
	[self dismissModalViewControllerAnimated:YES];
}
- (UIImage*)imageFromImageView:(UIImageView*)imageView
{
    CGSize size = imageView.frame.size;
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextRotateCTM(context, 2*M_PI);
    [imageView.layer renderInContext:context];
    UIImage *image =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
-(void)panGesture:(UIPanGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateEnded){
        CGPoint point = [gesture locationInView:_tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
        UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            NSString *str = [self.subjectDetailImages objectAtIndex:indexPath.row];
            UIImage *image = [UIImage imageNamed:str];
            CGRect frame = self.view.frame;
            //        frame.size.height = self.view.frame.size.height-44;
            frame.origin.y = 0;
            [self.customScrollView setFrame:frame];
            [self.customScrollView setZoomScale:1.0f];
            self.customScrollView.isZooming = YES;
            self.customScrollView.hidden = NO;
            self.customScrollView.delegate = self;
            self.customScrollView.userInteractionEnabled = YES;
            _customScrollView.scrollEnabled =  YES;
            _customScrollView.maximumZoomScale = 3.0f;
            _customScrollView.minimumZoomScale = 0.9f;
            _customScrollView.scrollsToTop  =  NO;
            _customScrollView.showsHorizontalScrollIndicator = YES;
            _customScrollView.showsVerticalScrollIndicator = YES;
            _customScrollView.backgroundColor = [UIColor whiteColor];
            self.customScrollView.clipsToBounds = YES;
            frame.origin.y  = 0;
            BOOL found = NO;
            for (UIView *subView in self.customScrollView.subviews) {
                if ([subView isKindOfClass:[UIImageView class]]) {
                    found = YES;
                    [((UIImageView *)subView)setImage:image];
                    break;
                }
            }
            if (!self.imageView) {
                self.imageView =  [[[UIImageView alloc]initWithFrame:self.view.bounds]autorelease];
            }else {
                [self.imageView setFrame:self.view.bounds];
            }
            if (!found) {
                [self.imageView setImage:image];
                [self.customScrollView addSubview:_imageView];
            }else {
                [self.imageView removeFromSuperview];
                self.imageView =  [[[UIImageView alloc]initWithFrame:self.view.bounds]autorelease];
                [self.imageView setImage:image];
                [self.customScrollView addSubview:_imageView];
            }
            _imageView.contentMode = UIViewContentModeScaleAspectFit;
            if ([ExpressionUtils isLandscapse]) {
                _imageView.contentMode = UIViewContentModeScaleAspectFill;
            }
            [self.imageView setAutoresizesSubviews:YES];
            [_customScrollView setContentSize:_imageView.frame.size];
        }
    }
}
-(void)tapGesture:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateEnded){
        CGPoint point = [gesture locationInView:_tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
        UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            NSString *str = [self.subjectDetailImages objectAtIndex:indexPath.row];
            UIImage *image = [UIImage imageNamed:str];
            CGRect frame = self.view.frame;
            //        frame.size.height = self.view.frame.size.height-44;
            frame.origin.y = 0;
            [self.customScrollView setFrame:frame];
            [self.customScrollView setZoomScale:1.0f];
            self.customScrollView.isZooming = YES;
            self.customScrollView.hidden = NO;
            self.customScrollView.delegate = self;
            self.customScrollView.userInteractionEnabled = YES;
            _customScrollView.scrollEnabled =  YES;
            _customScrollView.maximumZoomScale = 3.0f;
            _customScrollView.minimumZoomScale = 0.9f;
            _customScrollView.scrollsToTop  =  NO;
            _customScrollView.showsHorizontalScrollIndicator = YES;
            _customScrollView.showsVerticalScrollIndicator = YES;
            _customScrollView.backgroundColor = [UIColor whiteColor];
            self.customScrollView.clipsToBounds = YES;
            frame.origin.y  = 0;
            BOOL found = NO;
            for (UIView *subView in self.customScrollView.subviews) {
                if ([subView isKindOfClass:[UIImageView class]]) {
                    found = YES;
                    [((UIImageView *)subView)setImage:image];
                    break;
                }
            }
            if (!self.imageView) {
                self.imageView =  [[[UIImageView alloc]initWithFrame:self.view.bounds]autorelease];
            }else {
                [self.imageView setFrame:self.view.bounds];
            }
            if (!found) {
                [self.imageView setImage:image];
                [self.customScrollView addSubview:_imageView];
            }else {
                [self.imageView removeFromSuperview];
                self.imageView =  [[[UIImageView alloc]initWithFrame:self.view.bounds]autorelease];
                [self.imageView setImage:image];
                [self.customScrollView addSubview:_imageView];
            }
            _imageView.contentMode = UIViewContentModeScaleAspectFit;
            [self.imageView setAutoresizesSubviews:YES];
            [_customScrollView setContentSize:_imageView.frame.size];
        }
    }
}
#pragma mark - ScrollView Delegate
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
    if (scale < 1.0) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(exitZoom)];
        for (UIView *view in [self.customScrollView subviews]) {
            [view removeFromSuperview];
            break;
        }
        CGRect frame = self.view.frame;
        [self.customScrollView setFrame:frame];
        [self.customScrollView setContentSize:frame.size];
        [UIView commitAnimations];
        
    }
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}
-(void)exitZoom
{
    self.customScrollView.currentScale = 1.0;
    self.customScrollView.hidden = YES;
}
#pragma mark - UIActionSheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex ==0) {
        [self sendEmail];
    }else if (buttonIndex == 1){
        [self print];
    }else if(buttonIndex == 2){
        NSHTTPCookie *cookie;
        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (cookie in [storage cookies])
        {
            NSString* domainName = [cookie domain];
            NSLog(@"domainName:%@",domainName);
            [storage deleteCookie:cookie];
        }
//        [self LoginFacebook];
        if (FBSession.activeSession.isOpen) {
            [self sendRequests];
        } else {
            FBSession *newSession;
            newSession = [[FBSession alloc]initWithAppID:nil permissions:nil urlSchemeSuffix:nil tokenCacheStrategy:nil];
//            [FBSession openActiveSessionWithReadPermissions:nil
//                                               allowLoginUI:YES
//                                          completionHandler:^(FBSession *session,
//                                                              FBSessionState status,
//                                                              NSError *error) {
//                    if (error) {
//                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//                        [alert show];
//                    } else if (FB_ISSESSIONOPENWITHSTATE(status)) {
//                          [self sendRequests];
//                    }
//              }];
            NSArray *writepermissions = [[NSArray alloc] initWithObjects:
                                         @"publish_stream",
                                         @"publish_actions",
                                         nil];
            [FBSession openActiveSessionWithPublishPermissions:writepermissions defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                if (error) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alert show];
                } else if (FB_ISSESSIONOPENWITHSTATE(status)) {
                    [self sendRequests];
                }
            }];
        }

    }
}
#pragma mark - FaceBook Method
-(void)LoginFacebook
{
    FBSession *newSession = [_userManager switchToUserInSlot:(indexSession)];
//    indexSession ++ ;
    if (newSession.state == FBSessionStateCreatedTokenLoaded) {
//        [self LoginFacebook];
//        return ;
    }
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    [newSession openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error)
     {
         if (error) {
             NSLog(@"error");
         }
         if (newSession.state == FBSessionStateOpen) {
             [FBSession setActiveSession:newSession];
             if (newSession.state == FBSessionStateOpen) {
                 FBRequest *me = [[FBRequest alloc] initWithSession:newSession
                                                          graphPath:@"me"];
                 [me startWithCompletionHandler:^(FBRequestConnection *connection,
                                                  NSDictionary<FBGraphUser> *result,
                                                  NSError *error) {
                     if (error) {
                         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Please try again later!" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
                         [alertView show];
                         [alertView release];
                         
                     }else{
                         if ([result objectForKey:@"id"]) {
                             [_userManager updateUser:result inSlot:indexSession];
                             [self sendRequests];
                             
                         }
                     }
                     [me release];
                     
                 }];

             }
             
         }else{
             if (newSession.state == FBSessionStateCreatedTokenLoaded)
             {
                 [newSession openWithCompletionHandler:^(FBSession *session,
                                                         FBSessionState status,
                                                         NSError *error) {
                     if (error) {
                         NSLog(@"%@",error.description);
                     }else{
                         NSLog(@"%@",error.description);
                     }
                 }];
             }
         }
     }];
    

}
- (void) performPublishAction:(void (^)(void)) action {
    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
        [FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:@"publish_actions"]
                                                   defaultAudience:FBSessionDefaultAudienceFriends
                                                 completionHandler:^(FBSession *session, NSError *error) {
                                                     if (!error) {
                                                         action();
                                                     }else{
                                                         [self showAlert:error.description];
                                                     }
                                                 }];
    } else {
        action();
    }
//    action();
    
}
- (void)showAlert:(NSString *)message
           result:(id)result
            error:(NSError *)error {
    
    NSString *alertMsg;
    NSString *alertTitle;
    if (error) {
        alertMsg = error.localizedDescription;
        alertTitle = @"Error";
    } else {
        NSDictionary *resultDict = (NSDictionary *)result;
        alertMsg = [NSString stringWithFormat:@"Successfully posted '%@'.\nPost ID: %@",
                    message, [resultDict valueForKey:@"id"]];
        alertTitle = @"Success";
    }
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                        message:alertMsg
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
}
-(void)sendRequests
{
    if (_arrayImage && _arrayImage.count >= 1) {
        UIImage *img = [UIImage imageNamed:[_arrayImage  objectAtIndex:0]];
        BOOL displayedNativeDialog = [FBNativeDialogs presentShareDialogModallyFrom:self
                                                                        initialText:nil
                                                                              image:img
                                                                                url:nil
                                                                            handler:nil];
        if (!displayedNativeDialog) {
            [self performPublishAction:^{
                [FBRequestConnection startForUploadPhoto:img
                                       completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                           if (error) {
                                               
                                           }
                                           [self showAlert:@"Photo Post" result:result error:error];
                                       }];
                
            }];
        }
    }
    
}
#pragma mark - App Cycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)sendEmail
{
    [self showMailPicker:nil];
}
-(void)showAlert:(NSString *)text
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Thông Báo" message:text delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];
    [alert release];
}
-(void)selectImage:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateEnded) {
        CGPoint point = [gesture locationInView:_tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
        if (indexPath) {
            NSString *imageName = [self.subjectDetailImages objectAtIndex:indexPath.row];
            if (!_arrayImage) {
                self.arrayImage = [NSMutableArray array];
            }
            if (![_arrayImage containsObject:imageName]) {
                [_arrayImage addObject:imageName];
            }else{
                [_arrayImage removeObject:imageName];
            }
        }
        [self showRightBarbutton];
        [self.tableView reloadData];
    }
    

}
-(void)sharePress:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"Share" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Email",@"Print",@"FaceBook", nil];
    [actionSheet showInView:self.view];
}
-(void)showRightBarbutton
{
    UIBarButtonItem *btnBar = [[UIBarButtonItem alloc]initWithTitle:@"Share" style:UIBarButtonItemStyleDone target:self action:@selector(sharePress:)];
    self.navigationItem.rightBarButtonItem = btnBar;
    [btnBar release];
    if (_arrayImage && _arrayImage.count >=1) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else{
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (!self.customScrollView) {
        self.customScrollView = [[[CustomScrollView alloc]initWithFrame:self.view.frame]autorelease];        
    }
    [self.view addSubview:self.customScrollView];
    self.customScrollView.hidden = YES;
    indexSession = 0;
    self.userManager = [[[SUUserManager alloc] init]autorelease];
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:_customScrollView action:@selector(gestureDoubleTap:)];
//    tapGesture.numberOfTapsRequired = 2;
//    [self.customScrollView addGestureRecognizer:tapGesture];
//    [tapGesture release];
    
    UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(selectImage:)];
    [self.tableView addGestureRecognizer:gesture];
    [gesture release];
    
    UIPinchGestureRecognizer *panGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(panGesture:)];
    [self.tableView addGestureRecognizer:panGesture];
    [panGesture release];
    [self showRightBarbutton];
    UITapGestureRecognizer *tapGesture;
    tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
    tapGesture.numberOfTapsRequired = 2;
    [self.tableView addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    self.banerView = [[[ADBannerView alloc]initWithFrame:CGRectMake(0, 460-50, _banerView.frame.size.width, _banerView.frame.size.height)]autorelease];
    
    _banerView.delegate =  self;
    _banerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin ;
    if ([ExpressionUtils isLandscapse]) {
        _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
    }else{
        _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
    }
    CGRect  rect = _banerView.frame;
    rect.origin.x = (self.view.frame.size.width - _banerView.frame.size.width)/2;
    rect.origin.y = self.view.frame.size.height - _banerView.frame.size.height;
    _banerView.frame = rect;
    [self.view addSubview:_banerView];
    [self.view bringSubviewToFront:_banerView];
    _banerView.hidden = YES;
    
    switch (subjectNumber)
    {
        case 0:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"1Slide01.png",
                                        @"1Slide02.png",
                                        @"1Slide03.png",
                                        @"1Slide04.png",
                                        @"1Slide05.png",
                                        @"1Slide06.png",
                                        @"1Slide07.png",
                                        @"1Slide08.png",
                                        @"1Slide09.png",
                                        @"1Slide10.png",
                                        @"1Slide11.png",
                                        @"1Slide12.png",
                                        @"1Slide13.png",
                                        @"1Slide14.png",
                                        @"1Slide15.png",
                                        @"1Slide16.png",nil];
            break;
        case 1:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"2Slide01.png",
                                        @"2Slide02.png",
                                        @"2Slide03.png",
                                        @"2Slide04.png",
                                        @"2Slide05.png",
                                        @"2Slide06.png",
                                        @"2Slide07.png",
                                        @"2Slide08.png",
                                        @"2Slide09.png",
                                        @"2Slide10.png",
                                        @"2Slide11.png",
                                        @"2Slide12.png",
                                        @"2Slide13.png",
                                        @"2Slide14.png",
                                        @"2Slide15.png",nil];
            break;
        case 2:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"3Slide01.png",
                                        @"3Slide02.png",
                                        @"3Slide03.png",
                                        @"3Slide04.png",
                                        @"3Slide05.png",
                                        @"3Slide06.png",
                                        @"3Slide07.png",
                                        @"3Slide08.png",
                                        @"3Slide09.png",
                                        @"3Slide10.png",
                                        @"3Slide11.png",
                                        @"3Slide12.png",
                                        @"3Slide13.png",nil];
            break;
        case 3:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"4Slide01.png",
                                        @"4Slide02.png",
                                        @"4Slide03.png",
                                        @"4Slide04.png",
                                        @"4Slide05.png",
                                        @"4Slide06.png",
                                        @"4Slide07.png",
                                        @"4Slide08.png",
                                        @"4Slide09.png",
                                        @"4Slide10.png",
                                        @"4Slide11.png",
                                        @"4Slide12.png",
                                        @"4Slide13.png",nil];
            
            break;
            
        case 4:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"5Slide01.png",
                                        @"5Slide02.png",
                                        @"5Slide03.png",
                                        @"5Slide04.png",
                                        @"5Slide05.png",
                                        @"5Slide06.png",
                                        @"5Slide07.png",nil];
            
            break;
        case 5:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"6Slide01.png",
                                        @"6Slide02.png",
                                        @"6Slide03.png",
                                        @"6Slide04.png",
                                        @"6Slide05.png",nil];
            
            break;
        case 6:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"7Slide01.png",
                                        @"7Slide02.png",
                                        @"7Slide03.png",
                                        @"7Slide04.png",
                                        @"7Slide05.png",
                                        @"7Slide06.png",
                                        @"7Slide07.png",nil];
            
            break;
            
        case 7:
            self.subjectDetailImages = [[NSArray alloc]
                                        initWithObjects:@"AboutVNLite.png",nil];
            
            break;
            
            
        default:
            break;
            
    }
    
}
-(BOOL)shouldAutorotate
{
    return YES;
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
     [self scrollViewDidEndZooming:self.customScrollView withView:nil atScale:0.5];
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
     [self scrollViewDidEndZooming:self.customScrollView withView:nil atScale:0.5];
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    CGRect rect = self.view.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;
    [self.customScrollView setFrame:rect];
    if (_banerView) {
        if ([ExpressionUtils isLandscapse]) {
            _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
        }else{
            _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
        }
        rect = _banerView.frame;
        rect.origin.x = (self.view.frame.size.width - _banerView.frame.size.width)/2;
        rect.origin.y = self.view.frame.size.height - _banerView.frame.size.height;
        _banerView.frame = rect;
        
    }
    [_tableView reloadData];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return subjectDetailImages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"CellDetail";
    UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell1) {
        cell1 = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
    }
    
    // Configure the cell...
    CGFloat h = [self tableView:_tableView heightForRowAtIndexPath:indexPath];
    UIImageView *imageViewDetail = (UIImageView *)[cell1 viewWithTag:1000];
    if (!imageViewDetail) {
        imageViewDetail = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cell1.bounds.size.width, h)];
        imageViewDetail.tag =  1000;
        [cell1 addSubview:imageViewDetail];
        [imageViewDetail release];
    }
    [imageViewDetail setFrame:CGRectMake(0, 0, self.view.frame.size.width,h)];
    
    self.title= subjectName;
    UIImage *DetailPhoto = [UIImage imageNamed: [self.subjectDetailImages objectAtIndex: [indexPath row]]];
    [imageViewDetail setImage:DetailPhoto];
    
    UIImageView *imageView = (UIImageView *)[cell1 viewWithTag:9999];
    if (!imageView) {
        imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"selected"]];
        imageView.tag =  9999;
        [imageView setFrame:CGRectMake(cell1.frame.size.width - 50 -10, (h - 50)/2, 50, 50)];
        [cell1 addSubview:imageView];
        [imageView release];
    }
    [imageView setFrame:CGRectMake(cell1.frame.size.width - 50 -10, (h - 50)/2, 50, 50)];
    [imageView setImage:[UIImage imageNamed:@"selected"]];
    NSString *str = [self.subjectDetailImages objectAtIndex:indexPath.row];
    if ([_arrayImage containsObject:str]) {
        imageView.hidden = NO;
    }else{
        imageView.hidden = YES;
    }

    
    
    
    
    return cell1;
}


- (CGFloat) tableView: (UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath  *) indexPath
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    
    
    UIImage *DetailPhoto = [UIImage imageNamed: [self.subjectDetailImages objectAtIndex: [indexPath row]]];
    if (orientation == UIDeviceOrientationLandscapeLeft ||
        orientation == UIDeviceOrientationLandscapeRight)
    {
        d=480;
    }
    
    else
        d=320;
    
    
    cellHeight=(d*(DetailPhoto.size.height/DetailPhoto.size.width));
    
    
    return cellHeight;
}
#pragma mark -
#pragma mark -TableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
#pragma mark-
#pragma mark - Adbaner Delegate
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
    _banerView.hidden = NO;
    CGRect  rect = _banerView.frame;
    rect.origin.x = (self.view.frame.size.width - _banerView.frame.size.width)/2;
    rect.origin.y = self.view.frame.size.height - _banerView.frame.size.height;
    _banerView.frame = rect;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1];
        [banner setAlpha:1];
        rect = self.tableView.frame;    
        if ((rect.size.height + _banerView.frame.size.height) > self.view.frame.size.height) {
            rect.size.height -= _banerView.frame.size.height;
        }
        self.tableView.frame = rect;
        [UIView commitAnimations];
        
        self.bannerIsVisible2 = YES;
//    }
    
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    _banerView.hidden = YES;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1];
    [banner setAlpha:0];
    CGRect rect = self.tableView.frame;
    rect.size.height = self.view.frame.size.height;
    self.tableView.frame = rect;
    [UIView commitAnimations];
    
    
    self.bannerIsVisible2 = NO;

}

@end

@implementation CustomScrollView
@synthesize isZooming;
@synthesize currentScale;
-(void)gestureDoubleTap:(UIGestureRecognizer *)gesture
{
    currentScale += 0.8;
    [self setZoomScale:currentScale animated:YES];
}
-(id)init
{
    self =  [super init];
    return self;
}

-(id)initWithFrame:(CGRect)frame
{
    self= [super initWithFrame:frame];
    if (self) {
        currentScale = 1.0;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gestureDoubleTap:)];
        tapGesture.numberOfTapsRequired = 2;
        [self addGestureRecognizer:tapGesture];
        [tapGesture release];
    }
    return self;
}


@end
